package com.anne.fish.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.anne.fish.service.LimitWordManager;
import com.anne.fish.model.LimitWord;
import com.anne.fish.webapp.action.BaseAction;

import java.util.List;

public class LimitWordAction extends BaseAction implements Preparable {
    private LimitWordManager limitWordManager;
    private List limitWords;
    private LimitWord limitWord;
    private Long id;
    private String query;

    public void setLimitWordManager(LimitWordManager limitWordManager) {
        this.limitWordManager = limitWordManager;
    }

    public List getLimitWords() {
        return limitWords;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String limitWordId = getRequest().getParameter("limitWord.id");
            if (limitWordId != null && !limitWordId.equals("")) {
                limitWord = limitWordManager.get(new Long(limitWordId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        limitWords = limitWordManager.search(query, LimitWord.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public LimitWord getLimitWord() {
        return limitWord;
    }

    public void setLimitWord(LimitWord limitWord) {
        this.limitWord = limitWord;
    }

    public String delete() {
        limitWordManager.remove(limitWord.getId());
        saveMessage(getText("limitWord.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            limitWord = limitWordManager.get(id);
        } else {
            limitWord = new LimitWord();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (limitWord.getId() == null);

        limitWordManager.save(limitWord);

        String key = (isNew) ? "limitWord.added" : "limitWord.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}